import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Save, X, Plus, Trash2, Shield } from "lucide-react";

const StringArrayEditor = ({ title, items, onUpdate, placeholder }) => {
  const safeItems = Array.isArray(items) ? items : [];

  const handleAddItem = () => onUpdate([...safeItems, ""]);
  const handleUpdateItem = (index, value) => {
    const newItems = [...safeItems];
    newItems[index] = value;
    onUpdate(newItems);
  };
  const handleRemoveItem = (index) =>
    onUpdate(safeItems.filter((_, i) => i !== index));

  return (
    <div className="space-y-3 p-4 border rounded-lg bg-gray-50/50">
      <h4 className="font-medium text-gray-800">{title}</h4>
      <div className="space-y-2">
        {safeItems.map((item, index) => (
          <div key={index} className="flex items-center gap-2">
            <Input
              value={item}
              onChange={(e) => handleUpdateItem(index, e.target.value)}
              placeholder={`${placeholder} ${index + 1}`}
            />
            <Button
              variant="ghost"
              size="icon"
              onClick={(e) => {
                e.stopPropagation(); // 阻止冒泡到父元素
                e.preventDefault(); // 阻止默认行为（如果有）
                handleRemoveItem(index);
              }}
              className="text-red-500 hover:text-red-700 shrink-0"
            >
              <Trash2 className="w-4 h-4" />
            </Button>
          </div>
        ))}
      </div>
      <Button
        variant="outline"
        size="sm"
        onClick={(e) => {
          e.stopPropagation(); // 阻止冒泡到父元素
          e.preventDefault(); // 阻止默认行为（如果有）
          handleAddItem();
        }}
        className="bg-white"
      >
        <Plus className="w-4 h-4 mr-2" /> 添加条目
      </Button>
    </div>
  );
};

export default function EmergencyMeasureTemplateForm({
  template,
  onSubmit,
  onCancel,
}) {
  const [localTemplate, setLocalTemplate] = useState({});

  useEffect(() => {
    setLocalTemplate(
      template || {
        code: "",
        category: "other",
        incidentType: "",
        description: "",
        immediateActions: [],
        requiredEquipment: "",
        responsiblePersonRole: "",
      }
    );
  }, [template]);

  const handleFieldChange = (field, value) => {
    setLocalTemplate((prev) => ({ ...prev, [field]: value }));
  };

  const handleActionChange = (actions) => {
    setLocalTemplate((prev) => ({ ...prev, immediateActions: actions }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit(localTemplate);
  };

  return (
    <Card
      className="mb-6 shadow-lg border-blue-200"
      id="emergency-measure-form"
    >
      <CardHeader className="bg-blue-50">
        <CardTitle className="flex items-center justify-between">
          <span className="flex items-center gap-2">
            <Shield className="w-5 h-5 text-blue-600" />
            {template
              ? `编辑应急措施: ${template.incidentType}`
              : "新建应急措施模板"}
          </span>
          <Button variant="ghost" size="icon" onClick={onCancel}>
            <X className="w-4 h-4" />
          </Button>
        </CardTitle>
      </CardHeader>
      <CardContent className="p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium mb-1">
                事故事件类型
              </label>
              <Input
                value={localTemplate.incidentType || ""}
                onChange={(e) =>
                  handleFieldChange("incidentType", e.target.value)
                }
                placeholder="例如: 高处坠落"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">模板编码</label>
              <Input
                value={localTemplate.code || ""}
                onChange={(e) => handleFieldChange("code", e.target.value)}
                placeholder="例如: EM-FALL-01"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium mb-1">事故类别</label>
              <Select
                value={localTemplate.category || "other"}
                onValueChange={(value) => handleFieldChange("category", value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择类别" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="personnelInjury">人员伤害</SelectItem>
                  <SelectItem value="equipmentFailure">设备故障</SelectItem>
                  <SelectItem value="fireAccident">火灾事故</SelectItem>
                  <SelectItem value="electricShock">触电事故</SelectItem>
                  <SelectItem value="fallFromHeight">高处坠落</SelectItem>
                  <SelectItem value="environmentalIncident">
                    环境事件
                  </SelectItem>
                  <SelectItem value="trafficAccident">交通事故</SelectItem>
                  <SelectItem value="other">其他</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">
              事故简要描述
            </label>
            <Textarea
              value={localTemplate.description || ""}
              onChange={(e) => handleFieldChange("description", e.target.value)}
              placeholder="简要说明该事故的特征和可能后果"
              rows={2}
            />
          </div>

          {/* <StringArrayEditor
            title="立即处置措施 (步骤化)"
            items={localTemplate.immediateActions}
            onUpdate={handleActionChange}
            placeholder="请输入处置措施"
          /> */}

          <div>
            <label className="block text-sm font-medium mb-1">
              立即处置措施
            </label>
            <Textarea
              value={localTemplate.immediateActions || ""}
              onChange={(e) =>
                handleFieldChange("immediateActions", e.target.value)
              }
              placeholder="发生事故后应立即采取的具体措施"
              rows={3}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium mb-1">
                所需应急设备/工具
              </label>
              <Input
                value={localTemplate.requiredEquipment || ""}
                onChange={(e) =>
                  handleFieldChange("requiredEquipment", e.target.value)
                }
                placeholder="例如: 急救箱, 担架, 灭火器"
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">
                主要负责人角色
              </label>
              <Input
                value={localTemplate.responsiblePersonRole || ""}
                onChange={(e) =>
                  handleFieldChange("responsiblePersonRole", e.target.value)
                }
                placeholder="例如: 现场负责人, 安全员"
              />
            </div>
          </div>

          <div className="flex justify-end gap-3 pt-4 border-t">
            <Button type="button" variant="outline" onClick={onCancel}>
              <X className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button type="submit" className="bg-blue-600 hover:bg-blue-700">
              <Save className="w-4 h-4 mr-2" />
              保存模板
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
